package servlets.adsServlets;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

import javax.servlet.annotation.MultipartConfig;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;

import managers.JsonManager;
import structures.AD;
import structures.User;

//MultipartConfig needed to read input files
@MultipartConfig
public class InsertNewADServlet extends HttpServlet {

	private static final String URLBASE = "http://localhost:8080/ISellToYouRESTWebService/InsertNewAD";
	private static final long serialVersionUID = -5621945048734064220L;

	protected void doPost(HttpServletRequest request, HttpServletResponse response){
		JsonManager jsonManager;
		jsonManager = new JsonManager();
		AD advertisement;
		User user;
		DataOutputStream dataOutputStream;
		StringBuilder stringBuilder;
		InputStream responseStream;
		BufferedReader responseStreamReader;
		String description, title, price, answer, line, payPalEmail;
		long idUser;
    	InputStream inputStream;
    	Part filePart;
        // gets values of text fields
    	description = request.getParameter("description").replace(" ", "%20");
    	title = request.getParameter("title").replace(" ", "%20");
    	price = request.getParameter("price");
    	payPalEmail = request.getParameter("payPalEmail");
    	user = (User) request.getSession().getAttribute("user");
        idUser = user.getId();
        
        inputStream = null; // input stream of the upload file
         
        
        try {
        	// obtains the upload file part in this multipart request
			filePart = request.getPart("photo");
        
	        if (filePart != null) {
	            inputStream = filePart.getInputStream();
	        }
        } catch (Exception e) {
			e.printStackTrace();
			return;
		} 
        
        response.setContentType("application/json");
		response.setCharacterEncoding("UTF-8");
		
		try {
			String attachmentName = filePart.getName();
			String attachmentFileName = "image.jpeg";
			String crlf = "\r\n";
			String twoHyphens = "--";
			String boundary =  "*****";
			
			HttpURLConnection httpUrlConnection = null;
			URL url = new URL(URLBASE + "?description="+ description + "&title="+ title + "&price="+ price + "&idUser="+ idUser + "&payPalEmail="+ payPalEmail );
			httpUrlConnection = (HttpURLConnection) url.openConnection();
			httpUrlConnection.setUseCaches(false);
			httpUrlConnection.setDoOutput(true);

			httpUrlConnection.setRequestMethod("POST");
			httpUrlConnection.setRequestProperty("Connection", "Keep-Alive");
			httpUrlConnection.setRequestProperty("Cache-Control", "no-cache");
			httpUrlConnection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
			
			dataOutputStream = new DataOutputStream(httpUrlConnection.getOutputStream());

			dataOutputStream.writeBytes(twoHyphens + boundary + crlf);
			dataOutputStream.writeBytes("Content-Disposition: form-data; name=\"" + attachmentName + "\";Content-Type=\"" + filePart.getContentType() + "\";filename=\"" + attachmentFileName + "\"" + crlf);
			dataOutputStream.writeBytes(crlf);
			dataOutputStream.write(getBytesFromInputStream(inputStream));
			
			dataOutputStream.writeBytes(crlf);
			dataOutputStream.writeBytes(twoHyphens + boundary + twoHyphens + crlf);
			dataOutputStream.flush();
			dataOutputStream.close();
			
			responseStream = new BufferedInputStream(httpUrlConnection.getInputStream());

			responseStreamReader = new BufferedReader(new InputStreamReader(responseStream));
			line = "";
			stringBuilder = new StringBuilder();
			while ((line = responseStreamReader.readLine()) != null)
			{
			    stringBuilder.append(line).append("\n");
			}
			responseStreamReader.close();

			answer = stringBuilder.toString();
			
			
			if(answer==null || !answer.startsWith("{"))
				throw new Exception();
			
			
			advertisement = jsonManager.toAD(answer);
			request.getSession().setAttribute("advertisement", advertisement);
			response.sendRedirect(request.getContextPath() + "/confirmNewAd.jsp");
		} catch (Exception e1) {
			request.getSession().setAttribute("error", "yes");
			try {
				response.sendRedirect(request.getContextPath() + "/newAd.jsp");
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
	public static byte[] getBytesFromInputStream(InputStream is)
	{
	    try (ByteArrayOutputStream os = new ByteArrayOutputStream();)
	    {
	        byte[] buffer = new byte[0xFFFF];
	        for (int len; (len = is.read(buffer)) != -1;)
	            os.write(buffer, 0, len);
	        os.flush();
	        return os.toByteArray();
	    }
	    catch (IOException e)
	    {
	        return null;
	    }
	}
	
}
